package com.webservicedemo;

import java.io.IOException;
import jcifs.ntlmssp.Type1Message;
import jcifs.ntlmssp.Type2Message;
import jcifs.ntlmssp.Type3Message;
import jcifs.util.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.NTLMScheme;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
 
public class WebServiceDemoActivity extends Activity
{
    /** Called when the activity is first created. */
      private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
      private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
      private static String NAMESPACE = "http://tempuri.org/";
      private static String METHOD_NAME1 = "FahrenheitToCelsius";
      private static String METHOD_NAME2 = "CelsiusToFahrenheit";
      private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
 
      Button btnFar,btnCel,btnClear;
      EditText txtFar,txtCel;
     
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_service_demo);
       
        btnFar = (Button)findViewById(R.id.btnFar);
        btnCel = (Button)findViewById(R.id.btnCel);
        btnClear = (Button)findViewById(R.id.btnClear);
        txtFar = (EditText)findViewById(R.id.txtFar);
        txtCel = (EditText)findViewById(R.id.txtCel);
       
        btnFar.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                	  new CallAsyncSP().execute("a");
//                        //Initialize soap request + add parameters
//                  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);       
//                 
//                  //Use this to add parameters
//                  request.addProperty("Fahrenheit",txtFar.getText().toString());
//                 
//                  //Declare the version of the SOAP request
//                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//                 
//                  envelope.setOutputSoapObject(request);
//                  envelope.dotNet = true;
//                 
//                  try {
//                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//                       
//                        //this is the actual part that will call the webservice
//                        androidHttpTransport.call(SOAP_ACTION1, envelope);
//                       
//                        // Get the SoapResult from the envelope body.
//                        SoapObject result = (SoapObject)envelope.bodyIn;
// 
//                        if(result != null)
//                        {
//                              //Get the first property and change the label text
//                              txtCel.setText(result.getProperty(0).toString());
//                        }
//                        else
//                        {
//                              Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
//                        }
//                  } catch (Exception e) {
//                        e.printStackTrace();
//                  }
                  }
            });
       
        btnCel.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        //Initialize soap request + add parameters
                  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);       
                 
                  //Use this to add parameters
                  request.addProperty("Celsius",txtCel.getText().toString());
                 
                  //Declare the version of the SOAP request
                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                 
                  envelope.setOutputSoapObject(request);
                  envelope.dotNet = true;
                 
                  try {
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                       
                        //this is the actual part that will call the webservice
                        androidHttpTransport.call(SOAP_ACTION2, envelope);
                       
                        // Get the SoapResult from the envelope body.
                        SoapObject result = (SoapObject)envelope.bodyIn;
 
                        if(result != null)
                        {
                              //Get the first property and change the label text
                              txtFar.setText(result.getProperty(0).toString());
                        }
                        else
                        {
                              Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        }
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
                  }
            });
       
        btnClear.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        txtCel.setText("");
                        txtFar.setText("");
                  }
            });
    }
}

class CallAsync extends AsyncTask<String, Void, String>{
	private Exception ex;
    /** Called when the activity is first created. */
    private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
    private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
    private static String NAMESPACE = "http://tempuri.org/";
    private static String METHOD_NAME1 = "FahrenheitToCelsius";
    private static String METHOD_NAME2 = "CelsiusToFahrenheit";
    private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";

	@Override
	protected String doInBackground(String... arg0) {
		// TODO Auto-generated method stub
	      //Initialize soap request + add parameters
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);       
        String temp = "a";
        //Use this to add parameters
        request.addProperty("Fahrenheit","98");
       
        //Declare the version of the SOAP request
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
       
        envelope.setOutputSoapObject(request);
        envelope.dotNet = true;
       
        try {
              HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
             
              //this is the actual part that will call the webservice
              androidHttpTransport.call(SOAP_ACTION1, envelope);
             
              // Get the SoapResult from the envelope body.
              SoapObject result = (SoapObject)envelope.bodyIn;

              if(result != null)
              {
                    //Get the first property and change the label text
                    //txtCel.setText(result.getProperty(0).toString());
            	  temp = result.getProperty(0).toString();
            	  return temp;
              }
              else
              {
                    //Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
              }
        } catch (Exception e) {
              e.printStackTrace();
        }
		return temp;
	}
}

class CallAsyncSP extends AsyncTask<String, Void, String>{

	@Override
	protected String doInBackground(String... arg0) {
		String temp = "a";
		 HttpClient httpclient = new DefaultHttpClient();        
	        ((AbstractHttpClient) httpclient).getAuthSchemes().register("ntlm",new NTLMSchemeFactory());

	        NTCredentials creds = new NTCredentials("administrator", "Hai123456", "", "");

	        ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
	        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000); 
	        
	        HttpPost httppost = new HttpPost("http://192.168.1.100/_vti_bin/Lists.asmx");
	        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
	        
	        
	        try {
	            StringEntity se = new StringEntity( "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"><listName>Shared Documents</listName><rowLimit>50</rowLimit></GetListItems></soap:Body></soap:Envelope>", HTTP.UTF_8);
	            se.setContentType("text/xml");
	            httppost.setEntity(se); 

	            HttpResponse httpresponse = httpclient.execute(httppost);
	            HttpEntity resEntity = httpresponse.getEntity();

	            temp = "Status OK: \n" + EntityUtils.toString(resEntity);
	   
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	            temp = "Status NOT OK: \n" + e.getMessage();
	        } catch (IOException e) {
	            e.printStackTrace();
	            temp = "Status NOT OK: \n" + e.getMessage();
	        }
		return temp;
	}
}

//JCIFSEngine 
class JCIFSEngine implements NTLMEngine {

    public String generateType1Msg(
            String domain, 
            String workstation) throws NTLMEngineException {

        Type1Message t1m = new Type1Message(
                Type1Message.getDefaultFlags(),
                domain,
                workstation);
        return Base64.encode(t1m.toByteArray());
    }

    public String generateType3Msg(
            String username, 
            String password, 
            String domain,
            String workstation, 
            String challenge) throws NTLMEngineException {
        Type2Message t2m;
        try {
            t2m = new Type2Message(Base64.decode(challenge));
        } catch (IOException ex) {
            throw new NTLMEngineException("Invalid Type2 message", ex);
        }
        Type3Message t3m = new Type3Message(
                t2m, 
                password, 
                domain, 
                username, 
                workstation, 0);
        return Base64.encode(t3m.toByteArray());
    }

}

//NTLM Scheme factory 
class NTLMSchemeFactory implements AuthSchemeFactory {

    public AuthScheme newInstance(final HttpParams params) {
        return new NTLMScheme(new JCIFSEngine());
    }
    
}
